<template>
	<view class="Recharge_content Transfer_content">
		<view class="kuang">
			<view class="title">
				<view class="inline-block left">
					<image src="../../static/image/left.png" mode=""  @tap="back"></image>
				</view>
			</view>
			<view class="vote_title">
				<image src="../../static/image/node_icon.png"></image>
				<text>{{i18n.Recharge_content_reword}}</text>
			</view>
			<view class="choice" style="margin-top: 72upx;">
				<text>{{i18n.Recharge_content2}}</text>
				<view class="picker" style="width: 70%;height: 100%;">
					<picker @change="epoch_bindPickerChange" :value="curEpochIndex" :range="epochList">
							<view class="uni-input">{{i18n.Recharge_content3}}{{curSelectedEpochIndextext}}{{i18n.Recharge_content4}}</view>
					</picker>
					<image src="../../static/image/bottom.png" class="down" style="width: 24upx;height: 12upx;margin-left: 15upx;margin-top: 14upx;" ></image>
				</view>
			</view>
		
			<view class="choice" >
				<text>{{i18n.Recharge_content9}}</text>
				<view class="picker" style="width: 70%;height: 100%;">
					<picker @change="candidate_bindPickerChange" :value="curCandidateNameIndex" :range="curCandidateList">
							<view class="uni-input">{{curCandidateList[curCandidateNameIndex]}}</view>
					</picker>
					<image src="../../static/image/bottom.png" class="down" style="width: 24upx;height: 12upx;margin-left: 15upx;margin-top: 14upx;"></image>
				</view>
			</view>
			
			<view class="encourage_data">
				<view class="encourage_item">
					<view>{{i18n.Recharge_content5}}</view>
					<text>{{candidateReward}}  OEX</text>
				</view>
				<view class="encourage_item">
					<view>{{i18n.Recharge_content6}}</view>
					<text>{{allVotersReward}}  OEX</text>
				</view>
				<view class="encourage_item">
					<view>{{i18n.Recharge_content10}}</view>
					<text>{{allVote4Candidate}}  OEX</text>
				</view>
				<view class="encourage_item">
					<view>{{i18n.Recharge_content11}}</view>
					<text>{{yourVote4Candidate}}  OEX</text>
				</view>
				<view class="encourage_item">
					<view>{{i18n.Recharge_content7}}</view>
					<text>{{voterReward}}  OEX</text>
				</view>
			</view>
			
			
			<button class="bottombutton" @tap="getReward" :disabled="isDisable">
				{{i18n.Recharge_content8}}
			</button>
		</view>


	</view>
</template>

<script>
	import * as oexWeb3 from 'oex-web3';
	import BigNumber from 'bignumber.js';
	
	export default {
		computed: {
			i18n() {
				return this.$t('user')
			}
		},
		data() {
			return {
				 epochCandidateNames: {},
				 curCandidateList: [],
				 curEpoch: 0,
				 curCandidateName: "",
				 curEpochIndex: 0,
				 curCandidateNameIndex: 0,
				 curEpoch:0,
				 epochList: [],
				 voterMap: {},
				 accountName: "",
				 candidateReward: 0,
				 allVotersReward: 0,
				 voterReward: 0,
				 allVote4Candidate: 0,
				 yourVote4Candidate: 0,
				 candidateMap: {},
				 curSelectedEpochIndex:"",
				 curSelectedEpochIndextext:"1",
					 isDisable:false
			}
		},
		onLoad() {
			const accountInfo = uni.getStorageSync("account_info");
			this.accountName = accountInfo.accountName;
			
			this.$Web3Wrapper.getCurrentBlock(false).then(block => {
				this.$Web3Wrapper.getEpochByHeight(block.number).then(epoch => {
					this.curEpoch = epoch;
					const epochList = [];
					for (var i = 1; i < epoch - 1; i++) {
						epochList.push(i);
					}
					this.epochList = epochList;
				});
			});
			
		},
		methods: {
			epoch_bindPickerChange(e) {
				this.curSelectedEpochIndex = e.detail.value;
				this.curSelectedEpochIndextext = Number(e.detail.value) +1;
				this.curSelectedEpoch = this.epochList[e.detail.value];
				this.curCandidateNameIndex = 0;
				const candidateEpoch = this.curSelectedEpoch + 1;
				if (this.candidateMap[candidateEpoch] == null) {
					this.candidateMap[candidateEpoch] = {}
					this.$Web3Wrapper.getCandidates(candidateEpoch, true).then(candidates => {
						candidates.map(candidate => {
							this.candidateMap[candidateEpoch][candidate.name] = candidate;
						});
					});
				}
				// if (this.epochCandidateNames[candidateEpoch] == null) {
				// 	this.epochCandidateNames[candidateEpoch] = [];
				// 	this.$Web3Wrapper.getValidCandidates(candidateEpoch).then(validCandidates => {
				// 		this.epochCandidateNames[candidateEpoch].push(...validCandidates.activatedCandidateSchedule);
				// 		this.curCandidateList = this.epochCandidateNames[candidateEpoch];
				// 		console.log(this.curCandidateList);
				// 	});
				// }
				
				const _this = this;
				this.voterMap[this.curSelectedEpoch] = {}
				this.$Web3Wrapper.getVotersByVoter(this.curSelectedEpoch, this.accountName, true).then(voterInfos => {
					this.curCandidateList = [];
					if (voterInfos == null || voterInfos.length == 0) {
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '您未在此周期投过票':'You did NOT vote in this epoch.');
						//this.curCandidateList.push('未投票');
						return;
					}
					voterInfos.map(voterInfo => {
						this.voterMap[this.curSelectedEpoch][voterInfo.candidate] = voterInfo.quantity;
						this.curCandidateList.push(voterInfo.candidate);
					});
				});
			},
			candidate_bindPickerChange: function(e) {
				this.curCandidateNameIndex = e.target.value;
				this.curCandidateName = this.curCandidateList[this.curCandidateNameIndex];
				this.caculateReward();
			},
			caculateReward: function() {
				const candidateEpoch = this.curSelectedEpoch + 1;
				const candidateInfo = this.candidateMap[candidateEpoch][this.curCandidateName];
				if (this.curSelectedEpoch > 1) {
					this.$Web3Wrapper.getCandidate(this.curSelectedEpoch, this.curCandidateName).then(preCandidateInfo => {
						this.candidateReward = new BigNumber(candidateInfo.reward).minus(new BigNumber(preCandidateInfo.reward)).shiftedBy(18 * -1).toNumber();
						this.allVotersReward = this.candidateReward / 5;
						this.allVote4Candidate = preCandidateInfo.totalQuantity - preCandidateInfo.quantity;
						this.yourVote4Candidate = this.voterMap[this.curSelectedEpoch][this.curCandidateName];
						if (this.voterMap[this.curSelectedEpoch][this.curCandidateName] != null)
							this.voterReward = this.allVotersReward * this.yourVote4Candidate / this.allVote4Candidate;
						else 
							this.voterReward = 0;
					});
				} else {
					this.candidateReward = new BigNumber(candidateInfo.reward).shiftedBy(18 * -1).toNumber();
					this.allVotersReward = this.candidateReward / 5;
					if (this.voterMap[this.curSelectedEpoch][this.curCandidateName] != null)
						this.voterReward = this.allVotersReward * this.voterMap[this.curSelectedEpoch][this.curCandidateName] / candidateInfo.totalQuantity;
					else 
						this.voterReward = 0;
				}
			},
			back(){
				this.$CommonJS.navigateBack()
			},
			upper: function(e) {
					console.log(e)
			},
			lower: function(e) {
					console.log(e)
			},
			scroll: function(e) {
					console.log(e)
					//this.old.scrollTop = e.detail.scrollTop
			},
			getReward() {
			uni.showLoading({
				
			})
				const _this=this
				
				if (this.voterReward == 0 || this.curCandidateList.length == 0) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '您的激励数为0，无法领取激励':'Your incentive number is 0, unable to receive incentive');
					return;
				}
				if (this.curEpoch < 6) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '激励在第六周期后方可领取':'The incentive can only be collected after the fifth cycle');
					return;
				}
				const url = this.$API.appServeApi + this.$API.checkVoteReward + '?i18n_language=' + uni.getStorageSync('system_info');
				const data = {
								account : this.accountName,
								mineraccount: this.curCandidateName,
								cyclenum: this.curSelectedEpoch
							 }
								
				_this.isDisable=true   //点击一次时隔两秒后才能再次点击
				uni.request({
					url:url,
					method:"POST",
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					data:data,
					success(res) {
						_this.isDisable=false
						if(res.data.code == 200){
							uni.hideLoading()
							uni.showToast({
								// title: "成功提交请求，请稍后查看钱包余额"
								title:_this._i18n.locale == 'zh_CN' ? '成功提交请求，请稍后查看钱包余额':'The request has been submitted successfully. Please check your wallet balance later',
								icon:"none"
							});
						} else {
										uni.hideLoading()
							_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '领取失败：' + res.data.message:'Claim Failed:' + res.data.message);
						}
					},
					fail(error) {
									uni.hideLoading()
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请求失败' :'request was aborted');		
						_this.isDisable=false   //点击一次时隔两秒后才能再次点击
					}
				})
			}
		}
	}
</script>

<style lang="stylus">
	@import "../../static/stylus/nodeVote/node_vote.stylus"
</style>
